import { nextTick, reactive, ref } from "vue";
import { getMusicUrl, randomMusic } from "../../../utils/axiosApi";
import type { Music } from "../../../types/types";
import { ElMessage } from "element-plus";
import { AudioCache } from "../../../utils/audioCache";
import { musicStore } from "../../../store/musicStore";




// 存储用户输入的音乐信息（输入+选择）
export const userSelect = ref<{ iput: string; isele: string }>({
    iput: "", isele: ""
})


// 存储歌曲类型
export const musicType = reactive<{ label: string; value: string }[]>([
    { label: "流行音乐", value: "pop" }, { label: "热门音乐", value: "viral" },
    { label: "薛之谦", value: "modest" }, { label: "邓紫棋", value: "powerful" },
    { label: "电子音乐", value: "dj" }, { label: "治愈", value: "healing" },
]);




// 组件中存储音乐列表的变量
// 获取音乐信息
export function getMusicInfoList() {
    // 获取音乐属性，检查音乐属性是否存在
    const musicList = musicStore().musicList;
    if (musicList && musicList.length > 0) {
        return;
    } else {
        randomMusic();
    }
}




// 左侧菜单
export const leftNavigationmenus = reactive<{ key: string; label: string; }[]>([
    { key: "snow-music-list", label: "列表", }, { key: "snow-music-user-like", label: "喜欢" },
    { key: "snow-music-play-history", label: "历史" }, { key: "snow-music-hall", label: "乐馆" },
    { key: "snow-music-playlist", label: "歌单" }
])



const audioCache = ref(new AudioCache());

// 初始化IndexedDB
export async function initDB() {
    try {
        await audioCache.value.initDB()
    } catch (error) {
        console.error('IndexedDB 初始化失败:', error);
    }
}
// 初始化Audio
export function initAudio() {
    musicStore().audioElement! = new Audio();
    musicStore().audioElement!.addEventListener('timeupdate', () => {
        musicStore().currentMusic.currentTime = musicStore().audioElement!.currentTime || 0;
    });

    musicStore().audioElement!.addEventListener('loadedmetadata', () => {
        musicStore().currentMusic.duration = musicStore().audioElement!.duration || 0;
    });

    musicStore().audioElement!.addEventListener('ended', () => {
        ElMessage.info("播放下一首");
    });
}
export async function playMusic(musicKey: string): Promise<void> {
    // 新添加的条件处理
    // 1、如果是同一首歌且正在播放，则暂停音乐
    const isSameSong = musicStore().currentMusic.music_key === musicKey;
    if (isSameSong && musicStore().currentMusic.isPlaying) {
        if (musicStore().audioElement!) {
            musicStore().audioElement!.pause();
            musicStore().currentMusic.isPlaying = false;
        }
        return;
    }

    // 2、如果不是同一首歌且正在播放，则暂停当前音乐并且重置进度条
    if (!isSameSong && musicStore().currentMusic.isPlaying && musicStore().audioElement) {
        musicStore().audioElement!.pause();
        musicStore().currentMusic.currentTime = 0;
        musicStore().currentMusic.music_url = "";
    }

    // 先检查当前musicKey的音频链接是否已经缓存在了indexedDB中
    const cachedAudio = await audioCache.value.getAudioUrl(musicKey);
    let musicUrl: string | undefined;
    if (!cachedAudio) {
        musicUrl = await getMusicUrl(musicKey);
        if (musicUrl === undefined) {
            ElMessage.error("出现未知的错误，刷新页面尝试重新获取");
            return;
        }
        await audioCache.value.cacheAudioUrl(musicKey, musicUrl);
    } else {
        musicUrl = cachedAudio.url;
    }

    // 在这里执行播放音乐的操作
    // 1、检查当前点击的音乐是否存在于音乐列表中
    const music = musicStore().musicList.find((m: Music) => m.music_key === musicKey);
    if (!music) {
        ElMessage.error("音乐未找到");
        return;
    }

    const currentMusicInfo = {
        music_key: music.music_key,
        music_name: music.music_name,
        singer: music.singer,
        music_url: musicUrl,
        duration: 0,
        currentTime: 0,
        isPlaying: false,
        volume: 100,
        loopMode: 'off',
        shuffleMode: false
    };

    musicStore().setCurrentMusic(currentMusicInfo);

    // 在这里执行播放音乐的操作
    if (musicStore().audioElement) {
        // 确保 musicUrl 是有效的字符串
        if (typeof musicUrl !== 'string') {
            ElMessage.error("音乐链接无效");
            return;
        }

        // 设置新的音频源
        musicStore().audioElement!.src = musicUrl;
        musicStore().audioElement!.currentTime = 0; // 重置播放时间
        musicStore().audioElement!.load(); // 重新加载音频

        // 播放
        musicStore().audioElement!.play().then(() => {
            musicStore().currentMusic.isPlaying = true;
        }).catch(err => {
            console.error("播放失败：", err);
            ElMessage.error("播放失败，请检查音频文件");
        });
    } else {
        // 如果 audio.value 是 null，重新创建一个新的 Audio 对象            这里确保了audio始终不为null
        musicStore().audioElement! = new Audio(musicUrl);
        musicStore().audioElement!.currentTime = 0; // 重置播放时间
        musicStore().audioElement!.load(); // 重新加载音频

        // 播放
        musicStore().audioElement!.play().then(() => {
            musicStore().currentMusic.isPlaying = true;
        }).catch(err => {
            console.error("播放失败：", err);
            ElMessage.error("播放失败，请检查音频文件");
        });
    }

    // 最后执行存储历史播放记录的效果
    // 构建音乐对象
    const historyMusic: Music = {
        music_key: music.music_key,
        music_name: music.music_name,
        singer: music.singer
    }
    musicStore().setHistoryInfo(historyMusic);
}
// 切换播放/暂停
export function togglePlay() {
    if (musicStore().currentMusic.isPlaying) {
        pauseMusic();
    } else {
        if (musicStore().currentMusic.music_url) {
            playMusic(musicStore().currentMusic.music_key);
        } else if (musicStore().musicList.length > 0) {
            playMusic(musicStore().musicList[0].music_key);
        }
    }
}
// 暂停音乐
export function pauseMusic() {
    if (musicStore().audioElement!) {
        musicStore().audioElement!.pause();
        musicStore().currentMusic.isPlaying = false;
    }
}
// 播放上一首
export const playPreviousMusic = (): void => {
    if (!musicStore().currentMusic.music_key) return;
    const currentIndex = musicStore().musicList.findIndex(
        (m: Music) => m.music_key === musicStore().currentMusic.music_key
    );
    const prevIndex = (currentIndex - 1 + musicStore().musicList.length) % musicStore().musicList.length;

    playMusic(musicStore().musicList[prevIndex].music_key);
}
// 播放下一首
export const playNextMusic = (): void => {
    if (!musicStore().currentMusic.music_key) return;

    const currentIndex = musicStore().musicList.findIndex(
        (m: Music) => m.music_key === musicStore().currentMusic.music_key
    );

    const nextIndex = (currentIndex + 1) % musicStore().musicList.length;

    playMusic(musicStore().musicList[nextIndex].music_key);
}
export function moreMusicInfo(music: Music) {
    console.log(music)
}

// 处理拖动条
export function handleSeek(val: number) {
    if (!musicStore().audioElement!) return;

    // 获取拖动后的新时间位置
    // const newTime = Number((e.target as HTMLInputElement).value);

    // musicStore().currentMusic.currentTime = newTime;
    musicStore().currentMusic.currentTime = val;
}
// 处理拖动结束
export function handleSeekEnd(val: number) {
    if (!musicStore().audioElement!) return;

    // const newTime = Number((e.target as HTMLInputElement).value);


    // const seekTime = Math.min(newTime, musicStore().currentMusic.duration);


    // 更新音频当前时间
    musicStore().audioElement!.currentTime = val;

    // 如果当前是暂停状态，则拖动后不自动播放
    if (musicStore().currentMusic.isPlaying) {
        musicStore().audioElement!.play().catch(err => {
            console.error("跳转后播放失败！", err);
        })
    }
}

// 处理拖动音量事件
export function handleVolumeChange(val: number) {
    if (!musicStore().audioElement!) return;

    musicStore().audioElement!.volume = val / 100;     // 在这里需要进行一个转换，因为audio标签的volume的取值范围是0-1
}




// 添加喜欢的音乐



